<?php
header('Access-Control-Allow-Origin:*');
header('Content-Type:application/json');//加上这行,前端那边就不需要var result = $.parseJSON(data);
// 通过curl获取远程链接的excel文件 -- 并将其下载后放在 /www/wwwroot/excel.yangzuotang.top/excel
// 数据处理后暂时不删除
/*
备注说明：
如果远程文件的命名是英文的话可以直接下载就可以了，如果远程文件名是中文的，必须转换成utf-8的编码格式，然后再urlencode转换成url加密的格式，
php的代码程序的编码是gb2312。
*/

$url=$_GET['file'];

$save_dir = "/www/wwwroot/excel.yangzuotang.top/excel";
$url_arr = explode("/",$url);
$filename = rand(1, 10000).'_'.$url_arr[count($url_arr)-1];  //名称为1234_201910280545366597.xls
try
{
    $res = getFile($url, $save_dir, $filename,1);

    $deal_file_path = $save_dir.'/'.$filename;
//设置获取excel对象
    require_once('./Classes/PHPExcel/IOFactory.php');//引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
    $extension = strtolower( pathinfo($deal_file_path, PATHINFO_EXTENSION) );
    if ($extension =='xlsx') {
        $objReader = new PHPExcel_Reader_Excel2007();
        $objExcel = $objReader ->load($deal_file_path);
    } else if ($extension =='xls') {
        $objReader = new PHPExcel_Reader_Excel5();
        $objExcel = $objReader ->load($deal_file_path);
    } else if ($extension=='csv') {
        $PHPReader = new PHPExcel_Reader_CSV();
        //默认输入字符集
        $PHPReader->setInputEncoding('GBK');
        //默认的分隔符
        $PHPReader->setDelimiter(',');
        //载入文件
        $objExcel = $PHPReader->load($deal_file_path);
    }
    $sheet = $objExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow(); // 取得总行数
    $highestColumm = $sheet->getHighestColumn(); // 取得总列数
    $highestColumm= PHPExcel_Cell::columnIndexFromString($highestColumm); //字母列转换为数字列 如:AA变为27

//判断表头的真实长度
    for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
        $columnName = PHPExcel_Cell::stringFromColumnIndex($column);
        $value = $sheet->getCell($columnName.'1')->getValue();
        if ($value == ''){
            $highestColumm = $column;
            break;
        }
    }
    $data=[];
    for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
        for ($column = 0; $column < $highestColumm; $column++) {//列数是以第0列开始
            $columnName = PHPExcel_Cell::stringFromColumnIndex($column);
            $data[$row][$columnName.$row] = $sheet->getCellByColumnAndRow($column, $row)->getValue();
        }
    }
    // 将文件进行删除
    unlink($deal_file_path);
    $res = ['status'=>'success','msg'=>'文件处理数据成功','data'=>$data];
    echo json_encode($res);
}
//捕获异常
catch(Exception $e)
{
    echo 'Message: ' .$e->getMessage();
    $res = ['status'=>'fail','msg'=>'文件处理失败'];
    echo json_encode($res);
}


//页面编码要用gb2312
function getFile($url, $save_dir = '', $filename = '', $type = 0) {

    if (trim($url) == '') {
        return false;
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir.= '/';
    }
    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return false;
    }
    //获取远程文件所采用的方法
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $content = ob_get_contents();
        ob_end_clean();
    }
    //echo $content;
    $size = strlen($content);
    //文件大小
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $content);
    fclose($fp2);
    unset($content, $url);
    return array(
        'file_name' => $filename,
        'save_path' => $save_dir . $filename,
        'file_size' => $size
    );
}